package com.meatball.core.config.id

/**
 * TODO 生成雪花ID
 *
 * @property datacenterId
 * @property workerId
 */
class SnowflakeIdWorker(private val datacenterId: Long, private val workerId: Long) {
    // 开始时间截 (2015-01-01)
    private val twepoch = 1288834974657L

    // 机器id所占的位数
    private val workerIdBits = 5L
    // 数据标识id所占的位数
    private val datacenterIdBits = 5L
    // 支持的最大机器id，结果是31 (这个移位算法可以很快地计算出几位二进制数能表示的最大十进制数)
    private val maxWorkerId = -1L xor (-1L shl workerIdBits.toInt())
    // 支持的最大数据标识id，结果是31
    private val maxDatacenterId = -1L xor (-1L shl datacenterIdBits.toInt())

    // 序列在id中占的位数
    private val sequenceBits = 12L
    // 机器ID向左移12位
    private val workerIdShift = sequenceBits
    // 数据标识id向左移17位(12+5)
    private val datacenterIdShift = sequenceBits + workerIdBits
    // 时间截向左移22位(5+5+12)
    private val timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits
    // 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)
    private val sequenceMask = -1L xor (-1L shl sequenceBits.toInt())

    // 毫秒内序列(0~4095)
    private var sequence = 0L
    // 上次生成ID的时间截
    private var lastTimestamp = -1L

    init {
        // 检查datacenterId和workerId是否超过最大值，并且datacenterId和workerId不能小于0
        require(!(datacenterId > maxDatacenterId || datacenterId < 0)) {
            "数据中心ID不能大于$maxDatacenterId 或小于0"
        }
        require(!(workerId > maxWorkerId || workerId < 0)) {
            "工作机器ID不能大于$maxWorkerId 或小于0"
        }
    }

    // 获得下一个ID (该方法是线程安全的)
    @Synchronized
    fun nextId(): Long {
        var timestamp = timeGen()

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回拨过，这时抛出异常
        if (timestamp < lastTimestamp) {
            throw Exception("系统时钟回拨。拒绝为${lastTimestamp - timestamp}毫秒生成id")
        }

        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) and sequenceMask
            // 毫秒内序列溢出
            if (sequence == 0L) { // 阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp)
            }
        } else { // 时间戳改变，毫秒内序列重置
            sequence = 0L
        }

        // 上次生成ID的时间截
        lastTimestamp = timestamp

        // 移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) shl timestampLeftShift.toInt()) or
                (datacenterId shl datacenterIdShift.toInt()) or
                (workerId shl workerIdShift.toInt()) or
                sequence
    }

    // 阻塞到下一个毫秒，直到获得新的时间戳
    private fun tilNextMillis(lastTimestamp: Long): Long {
        var timestamp = timeGen()
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen()
        }
        return timestamp
    }

    // 返回以毫秒为单位的当前时间
    private fun timeGen(): Long = System.currentTimeMillis()
}